package sddz.foodmanage.dialog;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.foamtrace.photopicker.SelectModel;
import com.foamtrace.photopicker.intent.PhotoPickerIntent;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import sddz.foodmanage.R;
import sddz.foodmanage.base.BaseDialog;

/**
 * Created by Administrator on 2017/11/24.
 */

public class PhotoDialog extends BaseDialog implements View.OnClickListener {
    public static final int REQUEST_CAMERA_CODE = 741;
    private TextView tvCamera;
    private TextView tvPhoto;
    private TextView tvCancel;
    //相册(多选)
    public static final int SELECT_PHOTO = 0x123;
    //相机
    public static final int PICK_FROM_CAMERA = 0x234;
    private String imagePath;
    private ArrayList<String> photoList = new ArrayList<>();

    public PhotoDialog(Activity mActivity) {
        super(mActivity);
        initView();
        initListener();
    }

    private void initListener() {
        tvCamera.setOnClickListener(this);
        tvPhoto.setOnClickListener(this);
        tvCancel.setOnClickListener(this);
    }

    private void initView() {
        View view = LayoutInflater.from(mActivity).inflate(R.layout.choose_photo_layout, null);
        tvCamera = (TextView) view.findViewById(R.id.tv_camera);
        tvPhoto = (TextView) view.findViewById(R.id.tv_photo);
        tvCancel = (TextView) view.findViewById(R.id.tv_cancel);
        initPopupWindow(view);
    }

    public String getImagePath() {
        return imagePath;
    }

    @Override
    public void showDialog(View view) {
        super.showDialog(view);

    }

    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.tv_camera) {
            if (onChoosePhotoListener != null) {
                onChoosePhotoListener.openCamera();
            }
        } else if (i == R.id.tv_photo) {
            if (onChoosePhotoListener != null) {
                onChoosePhotoListener.openAlbum();
            }
        }
        dismissDialog();
    }

    /**
     * 进行拍照
     */
    public void openCamera() {

        if (!isPermission(Manifest.permission.CAMERA)) {
            applyPermission(Permission.CAMERA, new PermissionListener() {
                @Override
                public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                    openCamera();
                }

                @Override
                public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                    Toast.makeText(mActivity, "您拒绝了相机权限无法拍照", Toast.LENGTH_SHORT).show();
                }
            });
            return;
        }

        if (!isPermission(Manifest.permission.READ_EXTERNAL_STORAGE)) {
            applyPermission(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new PermissionListener() {
                @Override
                public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                    openCamera();
                }

                @Override
                public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                    Toast.makeText(mActivity, "您拒绝了储存权限无法进入相册", Toast.LENGTH_SHORT).show();
                }
            });
            return;
        }

        imagePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ElectronicCard";
        File file = new File(imagePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        long time = System.currentTimeMillis();
        String imageName = new SimpleDateFormat("yyMMddHHmmss").format(new Date(time));
        imagePath = imagePath + "/" + imageName + ".jpg";
        File imageFile = new File(imagePath);
        Uri uri = null;
        //兼容7.0拍照
        if (Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(mActivity,
                    mActivity.getPackageName() + ".provider", imageFile);
        } else {
            uri = Uri.fromFile(imageFile);
        }

        //拍照
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        //        intent.putExtra("android.intent.extras.CAMERA_FACING", 1);
        mActivity.startActivityForResult(intent, PICK_FROM_CAMERA);
    }

    /**
     * 打开相册的方法(多选)
     */
    public void openAlbum(final int zhang) {

        if (!isPermission(Manifest.permission.READ_EXTERNAL_STORAGE)) {
            applyPermission(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, new PermissionListener() {
                @Override
                public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                    openAlbum(zhang);
                }

                @Override
                public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                    Toast.makeText(mActivity, "您拒绝了储存权限无法进入相册", Toast.LENGTH_SHORT).show();
                }
            });
            return;
        }

        PhotoPickerIntent intent = new PhotoPickerIntent(mActivity);
        intent.setSelectModel(SelectModel.MULTI);
        intent.setShowCarema(false); // 是否显示拍照， 默认false
        intent.setMaxTotal(zhang); // 最多选择照片数量，默认为9
        intent.setSelectedPaths(photoList); // 已选中的照片地址， 用于回显选中状态
        mActivity.startActivityForResult(intent, SELECT_PHOTO);
    }

    /**
     * 打开相册的方法(多选)
     */
    public void openSingleAlbum(final int request) {

        if (!isPermission(Manifest.permission.READ_EXTERNAL_STORAGE)) {
            applyPermission(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, new PermissionListener() {
                @Override
                public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                    openSingleAlbum(request);
                }

                @Override
                public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                    Toast.makeText(mActivity, "您拒绝了储存权限无法进入相册", Toast.LENGTH_SHORT).show();
                }
            });
            return;
        }

        PhotoPickerIntent intent = new PhotoPickerIntent(mActivity);
        intent.setSelectModel(SelectModel.SINGLE);
        intent.setShowCarema(false); // 是否显示拍照， 默认false
        intent.setSelectedPaths(photoList); // 已选中的照片地址， 用于回显选中状态
        mActivity.startActivityForResult(intent, request);
    }

    /**
     * 打开相册的方法(单选)
     */
    public void openSingleAlbum() {

        if (!isPermission(Manifest.permission.READ_EXTERNAL_STORAGE)) {
            applyPermission(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, new PermissionListener() {
                @Override
                public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                    openSingleAlbum();
                }

                @Override
                public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                    Toast.makeText(mActivity, "您拒绝了储存权限无法进入相册", Toast.LENGTH_SHORT).show();
                }
            });
            return;
        }

        PhotoPickerIntent intent = new PhotoPickerIntent(mActivity);
        intent.setSelectModel(SelectModel.SINGLE);
        intent.setShowCarema(false); // 是否显示拍照， 默认false
        intent.setSelectedPaths(photoList); // 已选中的照片地址， 用于回显选中状态
        mActivity.startActivityForResult(intent, REQUEST_CAMERA_CODE);
    }

    public void setPhotoList(ArrayList<String> list) {
        photoList.clear();
        photoList.addAll(list);
    }

    private OnChoosePhotoListener onChoosePhotoListener;

    public void setOnChoosePhotoListener(OnChoosePhotoListener onChoosePhotoListener) {
        this.onChoosePhotoListener = onChoosePhotoListener;
    }

    public interface OnChoosePhotoListener {
        void openAlbum();

        void openCamera();
    }

    /**
     * 检查是否有该权限
     *
     * @param permission
     * @return
     */
    public boolean isPermission(String permission) {
        return (ContextCompat.checkSelfPermission(mActivity, permission)
                == PackageManager.PERMISSION_GRANTED);
    }

    /**
     * 申请应用授权
     *
     * @param permissions 权限数组（同一组权限的）
     */
    protected void applyPermission(String[] permissions, final PermissionListener listener) {
        applyPermission(permissions, 0x100, listener);
    }

    /**
     * 申请应用授权
     *
     * @param permissions 权限数组（同一组权限的）
     */
    protected void applyPermission(String[] permissions, int code, final PermissionListener listener) {
        //是否需要动态申请权限
        if (Build.VERSION.SDK_INT >= 23) {
            AndPermission.with(mActivity)
                    .requestCode(code)
                    .permission(permissions)
                    .callback(new PermissionListener() {
                        @Override
                        public void onSucceed(int requestCode, @android.support.annotation.NonNull List<String> grantPermissions) {
                            if (listener != null) {
                                listener.onSucceed(requestCode, grantPermissions);
                            }
                        }

                        @Override
                        public void onFailed(int requestCode, @android.support.annotation.NonNull List<String> deniedPermissions) {
                            if (listener != null) {
                                listener.onFailed(requestCode, deniedPermissions);
                            }
                        }
                    }).start();
        }
    }

}
